﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Framework.Core;
using Sector7.Framework.Enums;
using Sector7.Framework.Utility;
using Sector7.Medical.Biz;
using Sector7.Medical.Consts;
using Sector7.Medical.INFM.Windows;
using Sector7.Medical.EntityType;

namespace Sector7.Medical.INFM.Controls
{
    /// <summary>
    /// SickBedLevelSummaryControl.xaml 的交互逻辑
    /// </summary>
    public partial class SickBedLevelSummaryControl : AddModeControlBase
    {
        #region Accessor
        /// <summary>
        /// 病房信息
        /// </summary>
        public M7_SickBedLevel SickBedLevel
        {
            get { return m_entity as M7_SickBedLevel; }
            set { m_entity = value; }
        }
        #endregion

        #region Public functions
        #endregion

        #region Private functions

        /// <summary>
        /// Control Loaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SickBedLevelSummaryControl_Loaded(object sender, RoutedEventArgs e)
        {
            m_crud = CrudType.Unknown;

            Senvironments.ProgressWindow.Visibility = Visibility.Visible;

            SwitchPropertiyGroupsEnabledState(false);
            SwitchPropertiyActionButtonsState(CrudType.Unknown);
            //SwitchActionButtonsState(true);

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(LoadData_DoWork);
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 加载数据工作线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadData_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            GetData();

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        /// <summary>
        /// 读取所有病房信息列表
        /// </summary>
        private void GetData()
        {
            //1.获取所有病房信息列表
            m_bedLevelList = Agent_INFS.GetSickBedLevelList();
            //2.获取所有科室列表(执行科室)
            m_dept1List = Agent_INFS.GetDepartmentList(C_DepartmentFlags.DEPARTMENT);
            m_dept2List = Agent_INFS.GetDepartmentList(C_DepartmentFlags.SUB_DEPARTMENT);
            m_tmpDeptList.AddRange(m_dept1List);
            m_tmpDeptList.AddRange(m_dept2List);
            m_deptList.AddRange(m_tmpDeptList);

            //3.获取所有计费单位
            m_unitList = Agent_INFS.GetUnitListByFlags(C_UnitFlags.TIME_UNIT);
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            //加载所有病房信息列表
            ClientUtil.LoadItemsSource(dtgMain, m_bedLevelList);

            //加载所有执行科室的列表
            ClientUtil.LoadItemsSource(cbbDept, m_deptList);

            //加载计费单位信息列表
            ClientUtil.LoadItemsSource(cbbUnit, m_unitList);

            SwitchPropertiyActionButtonsStateByDataCount();

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isVisibility"></param>
        private void SwitchActionButtonsState(bool isVisibility)
        {
            //Visibility visibility = isVisibility ? Visibility.Visible : Visibility.Hidden;
            //btnOk.Visibility = visibility;
            //btnCancel.Visibility = visibility;

            btnAdd.IsEnabled = !isVisibility;
            btnModify.IsEnabled = !isVisibility;
            btnDelete.IsEnabled = !isVisibility;

            btnOk.IsEnabled = isVisibility;
            btnCancel.IsEnabled = isVisibility;
        }

        private void ckbSingleCount_Click(object obj, RoutedEventArgs e)
        {
            bool ckbChecked = (bool)ckbSingleCount.IsChecked;
            if (!ckbChecked)
            {
                txbLifeCycle.IsEnabled = false;
                cbbUnit.IsEnabled = false;
            }
            else
            {
                txbLifeCycle.IsEnabled = true;
                cbbUnit.IsEnabled = true;
            }
        }

        private void ClearSickBedLevelPropertity()
        {
            txbBedLevelId.Text = "";
            txbBedLevelName.Text = "";
            txbPrice.Text = "";
            ckbSingleCount.IsChecked = false;
            txbLifeCycle.Text = "";
            ckbIsValid.IsChecked = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isEnabled"></param>
        private void SwitchPropertiyGroupsEnabledState(bool isEnabled)
        {
            txbBedLevelId.IsEnabled = false;
            txbBedLevelName.IsEnabled = isEnabled;
            txbPrice.IsEnabled = false;
            cbbDept.IsEnabled = isEnabled;
            ckbSingleCount.IsEnabled = isEnabled;
            txbLifeCycle.IsEnabled = false;
            cbbUnit.IsEnabled = false;
            ckbIsValid.IsEnabled = isEnabled;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="crud"></param>
        private void SwitchPropertiyActionButtonsState(CrudType crud)
        {
            switch (crud)
            {
                case CrudType.Create:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    break;
                case CrudType.Read:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = true;
                    btnDelete.IsEnabled = true;
                    break;
                default:
                    btnAdd.IsEnabled = false;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    btnOk.IsEnabled = false;
                    btnCancel.IsEnabled = false;
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void SwitchPropertiyActionButtonsStateByDataCount()
        {
            if (m_bedLevelList.Count == 0)
            {
                SwitchPropertiyActionButtonsState(CrudType.Create);
                ClearSickBedLevelPropertity();
            }
            else
            {
                SwitchPropertiyActionButtonsState(CrudType.Read);
            }
        }

        /// <summary>
        /// 数据表选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dtgMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_SickBedLevel)
            {
                SwitchPropertiyActionButtonsState(CrudType.Read);

                M7_SickBedLevel bedLevel = dtgMain.SelectedItem as M7_SickBedLevel;
                ShowSickBedLevelInfor(bedLevel);
            }
            else
            {
                SwitchPropertiyGroupsEnabledState(false);
                SwitchActionButtonsState(false);
                SwitchPropertiyActionButtonsStateByDataCount();
                ClearSickBedLevelPropertity();
            }
        }

        /// <summary>
        /// 显示SickBedLevel Infor
        /// </summary>
        /// <param name="area"></param>
        private void ShowSickBedLevelInfor(M7_SickBedLevel bedLevel)
        {
            if (bedLevel != null)
            {
                txbBedLevelId.Text = bedLevel.BedLevelId.ToString();
                txbBedLevelName.Text = bedLevel.BedLevelName;
                txbLifeCycle.Text = Convert.ToDecimal(bedLevel.Lifecycle).ToString();
                cbbDept.SelectedValue = bedLevel.DeptId;
                //注:cbbDept使用SelectedValue赋不上值,建议使用SelectedValuePath=""
                txbPrice.Text = Convert.ToDecimal(bedLevel.Price).ToString();
                //cbbUnit.SelectedValue = 18;
                ckbIsValid.IsChecked = bedLevel.IsValid;
            }
            else
            {
                this.txbBedLevelId.Text = "";
                this.txbBedLevelName.Text = "";
                this.txbLifeCycle.Text = "";
                this.cbbDept.SelectedIndex = 0;
                this.txbPrice.Text = "";
                this.ckbIsValid.IsChecked = false;
            }
        }

        protected override bool CheckData()
        {
            m_errors.Clear();

            string bedLevelName = txbBedLevelName.Text.Trim();
            string price = txbPrice.Text.Trim();
            string lifeCycle = txbLifeCycle.Text.Trim();
            bool isSignleChk = (bool)ckbSingleCount.IsChecked;
            bool isValid = (bool)ckbIsValid.IsChecked;

            if (string.IsNullOrEmpty(bedLevelName))
            {
                m_errors.Add("病床等级", "不能为空!");
            }

            if (string.IsNullOrEmpty(price))
            {
                m_errors.Add("费用", "不能为空!");
            }
            else
            {
                try
                {
                    Convert.ToDecimal(price);
                }
                catch
                {
                    m_errors.Add("费用", "只能是数字!");
                }
            }

            if (isSignleChk)
            {
                if (string.IsNullOrEmpty(lifeCycle))
                {
                    m_errors.Add("计费周期", "不能为空!");
                }
                else
                {
                    try
                    {
                        Convert.ToDecimal(lifeCycle);
                    }
                    catch
                    {
                        m_errors.Add("计费周期", "只能是数字!");
                    }
                }
            }

            if (m_errors.Count == 0)
            {
                if (this.Crud == CrudType.Create)
                {
                    SickBedLevel = new M7_SickBedLevel();
                }
                SickBedLevel.BedLevelName = bedLevelName;
                SickBedLevel.Price = Convert.ToDecimal(price);
                SickBedLevel.DeptId = (cbbDept.SelectedItem as M7_Department).DeptId;
                if (isSignleChk)
                {
                    SickBedLevel.Lifecycle = Convert.ToDecimal(lifeCycle);
                    SickBedLevel.LifecycleUnit = ClientUtil.ConvertEntity(cbbUnit.SelectedItem, typeof(M7_Unit)) as M7_Unit;
                    SickBedLevel.LifecycleUnitId = (cbbUnit.SelectedItem as M7_Unit).UnitId;
                }
                SickBedLevel.IsValid = isValid;
            }
            return base.CheckData();
        }

        /// <summary>
        /// 添加病床等级
        /// </summary>
        protected override void AddData()
        {
            switch (m_crud)
            { 
                case CrudType.Create:
                    //1.添加病床等级
                    object bedLevelIdObj = Agent_INFS.AddSickBedLevel(SickBedLevel);
                    //2.同时添加病床等级信息到SickBedLevelItem
                    if (bedLevelIdObj != null)
                    {
                        SickBedLevel.BedLevelId = Convert.ToInt32(bedLevelIdObj);

                        SickBedLevel.Dept = m_deptList.Find(delegate(M7_Department __dept)
                        {
                            return __dept.DeptId == SickBedLevel.DeptId;
                        });

                        m_bedLevelList.Add(SickBedLevel);
                        dtgMain.Items.Refresh();
                        SelectSickBedLevelItem(SickBedLevel); 
                    }
                    SwitchPropertiyGroupsEnabledState(false);
                    SwitchActionButtonsState(false);
                    break;
                case CrudType.Update:
                    bool isChanged = false;
                    var delta = GetDelta("BedLevelId", ref isChanged);
                    if (isChanged)
                    {
                        Agent_INFS.UpdateSickBedLevel(delta);
                    }
                    SwitchPropertiyGroupsEnabledState(false);
                    SwitchActionButtonsState(false);
                    break;
            }
            base.AddData();
        }

        /// <summary>
        /// 选中Item颜色改变
        /// </summary>
        /// <param name="area"></param>
        private void SelectSickBedLevelItem(M7_SickBedLevel bedLevel)
        {
            if (dtgMain.Items.Contains(bedLevel))
            {
                dtgMain.SelectedItem = bedLevel;
            }
        }

        /// <summary>
        /// 初始化窗口
        /// </summary>
        /// <param name="crud">窗口操作类型</param>
        public new void InitializeControl(CrudType crud)
        {
            m_crud = crud;

            string prefix = string.Empty;
            switch (m_crud)
            {
                case CrudType.Create:
                    prefix = "新建";
                    InitializeForCreating();
                    break;
                case CrudType.Update:
                    prefix = "修改";
                    InitializeForUpdating();
                    break;
                default:
                    break;
            }

            InitializeForOthers();

            this.Tag = string.Format("{0}{1}", prefix, this.Tag);

            this.DataContext = m_entity;
        }

        /// <summary>
        /// 添加窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            InitializeControl(CrudType.Create);
        }

        /// <summary>
        /// 初始化添加
        /// </summary>
        protected override void InitializeForCreating()
        {
            SwitchPropertiyGroupsEnabledState(true);
            SwitchActionButtonsState(true);
            ClearSickBedLevelPropertity();

            base.InitializeForCreating();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModify_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_SickBedLevel)
            {
                var bedLevel = dtgMain.SelectedItem as M7_SickBedLevel;
                SickBedLevel = bedLevel;
                InitializeControl(CrudType.Update);
            }
        }

        /// <summary>
        /// 初始化修改
        /// </summary>
        protected override void InitializeForUpdating()
        {
            SwitchPropertiyGroupsEnabledState(true);
            SwitchActionButtonsState(true);
            ShowSickBedLevelInfor(SickBedLevel);

            base.InitializeForUpdating();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem is M7_SickBedLevel)
            {
                MessageBoxResult mbr = Alert.ShowDialog(AlertType.Question, "是否确定删除该病床等级信息?");
                if (mbr == MessageBoxResult.Yes)
                {
                    M7_SickBedLevel bedLevel = dtgMain.SelectedItem as M7_SickBedLevel;
                    int ret = Agent_INFS.DeleteSickBedLevel(bedLevel.BedLevelId);
                    if (ret > 0)
                    {
                        if (m_bedLevelList.Contains(bedLevel))
                        {
                            int index = dtgMain.Items.IndexOf(bedLevel);
                            index++;

                            m_bedLevelList.Remove(bedLevel);
                            dtgMain.Items.Refresh();

                            if (dtgMain.Items.Count != 0)
                            {
                                while (index >= dtgMain.Items.Count)
                                {
                                    index--;
                                }
                                dtgMain.SelectedIndex = index;
                            }
                        }

                        if (m_tempBedLevelList.Contains(bedLevel))
                        {
                            m_tempBedLevelList.Remove(bedLevel);
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 点击...按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            SelectedChargeItems();
        }

        private void SelectedChargeItems()
        {
            var selectedChargeItemsWindow = new SetSickBedLevelChargeItemWindow();
            selectedChargeItemsWindow.InitializeWindow(CrudType.Create);
            selectedChargeItemsWindow.AddSuccess += new EventHandler(SelectedChargeItems_AddSuccess);

            selectedChargeItemsWindow.ShowDialog();
        }

        private void SelectedChargeItems_AddSuccess(object sender, EventArgs e)
        {
            var bedLevelItemWindow = sender  as SetSickBedLevelChargeItemWindow;
            var newCountCost = bedLevelItemWindow.CountCost.ToString();
            txbPrice.Text = newCountCost;
            ClientUtil.LoadItemsSource(lsbDetails, bedLevelItemWindow.ChargeItem);
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {  
            SwitchPropertiyGroupsEnabledState(false);
            SwitchActionButtonsState(false);

            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_SickBedLevel)
            {
                M7_SickBedLevel bedLevel = dtgMain.SelectedItem as M7_SickBedLevel;
                ShowSickBedLevelInfor(bedLevel);
            }

            m_crud = CrudType.Unknown;
        }

        /// <summary>
        ///  Search关键值改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchBox_KeywordsChanging(object sender, KeyEventArgs e)
        {
            string keywords = searchBox.Keywords;
            m_bedLevelList = m_tempBedLevelList.FindAll(delegate(M7_SickBedLevel __sickBedLevel)
            {
                if (__sickBedLevel.BedLevelId.ToString().Contains(keywords) ||
                    __sickBedLevel.BedLevelName.Contains(keywords))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
            ClientUtil.LoadItemsSource(dtgMain, m_bedLevelList);
        }

        /// <summary>
        /// Search关键值重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchBox_KeywordsReset(object sender, EventArgs e)
        {
            m_bedLevelList.Clear();
            m_bedLevelList.AddRange(m_tempBedLevelList.ToArray());

            ClientUtil.LoadItemsSource(dtgMain, m_bedLevelList);
        }
        #endregion

        #region Structure
        public SickBedLevelSummaryControl()
        {
            InitializeComponent();
        }
        #endregion

        #region Inner Members
        /// <summary>
        /// 病床等级信息列表
        /// </summary>
        private List<M7_SickBedLevel> m_bedLevelList;

        /// <summary>
        /// 计费单位列表
        /// </summary>
        private List<M7_Unit> m_unitList;

        /// <summary>
        /// 获取所有一级科室列表
        /// </summary>
        private List<M7_Department> m_dept1List;

        /// <summary>
        /// 获取所有二级科室列表
        /// </summary>
        private List<M7_Department> m_dept2List;

        /// <summary>
        /// 获取所有科室列表
        /// </summary>
        private List<M7_Department> m_deptList = new List<M7_Department>();

        /// <summary>
        /// 获取所有临时科室列表
        /// </summary>
        private List<M7_Department> m_tmpDeptList = new List<M7_Department>();

        /// <summary>
        /// 病床等级临时信息列表
        /// </summary>
        private List<M7_SickBedLevel> m_tempBedLevelList = new List<M7_SickBedLevel>();
        #endregion
    }
}
